package com.xdf.xzymanagementsystem.util;

import com.xdf.xzymanagementsystem.enums.OpeEnum;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author chanchaw
 * @create 2023-04-08 15:41
 */
public class BeanUtils {
    public static boolean hasField(Class clazz, String fieldName) {
        Field field = ReflectionUtils.findField(clazz, fieldName);
        if (field != null) {
            return true;
        }
        return false;
    }

    public static boolean hasMethod(Class clazz, String methodName, Class[] argsType) {
        Method method = ReflectionUtils.findMethod(clazz, methodName, argsType);
        if (null != method) {
            return true;
        }
        return false;
    }

    /**
     * 为对象填充属性 createUser - 通过方法 setCreateUser
     * 在判断属性和方法都存在的情况下才会为对象属性赋值
     * 如果不存在则返回原始对象
     * 填写 request 中用户ID到属性 createUser 中
     * @param record 被装饰的对象
     * @return 装饰后的对象
     * @param <T> 泛型
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static <T> T fullFillRecord(T record, OpeEnum opeEnum) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        try {
            return setCreateUser(record, opeEnum);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T setCreateUser(T record, OpeEnum opeEnum)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
        String attrName = "";
        String methodName = "";
        String attrType = "";
        if(opeEnum == OpeEnum.NEW) {
            attrName = SystemConfig.ATTRIBUTE_NAME_CREATE_USER;
            methodName = SystemConfig.METHOD_NAME_CREATE_USER;
        }
        if(opeEnum == OpeEnum.UPDATE) {
            attrName = SystemConfig.ATTRIBUTE_NAME_LAST_USER;
            methodName = SystemConfig.METHOD_NAME_LAST_USER;
        }

        // 获取属性的数据类型
        Class<?> clazz = record.getClass();
        Field field = clazz.getDeclaredField(attrName);
        Class<?> fieldType = field.getType();
        attrType = fieldType.toString();

        boolean isString = fieldType.equals(Class.forName("java.lang.String"));
        boolean isInteger = fieldType.equals(Class.forName("java.lang.Integer"));

        if(!hasField(record.getClass(), attrName) || !hasMethod(record.getClass(), methodName, new Class[]{String.class})) return record;

        Method method1 = clazz.getDeclaredMethod(methodName, String.class);
        method1.invoke(record, ShiroUtils.getUserPKInteger());
        return record;
    }
}
